package com.leetcode.sorts.tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: WuPeng
 * @Date: 2021/6/3 3:26 下午
 *
 * 226.翻转二叉树
 *
 * tips：二叉树的前序、后序遍历都可以
 *
 */
public class InvertTree_226 {
    /**
     * 递归的方式翻转二叉树
     */
    public TreeNode invertTree(TreeNode root) {
        if (root == null){
            return null;
        }
        invertTree(root.left);
        invertTree(root.right);
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right= tmp;
        return root;
    }

    /**
     * 非递归（栈）的方式翻转二叉树
     */
    public TreeNode invertTree2(TreeNode root) {
        if (root == null){
            return null;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.push(root);
        while(!deque.isEmpty()){
            TreeNode node = deque.pop();
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right= tmp;
            if (node.left != null) deque.push(node.left);
            if (node.right != null) deque.push(node.right);
        }
        return root;
    }
}
